﻿using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ProLinq.Tests.Interception
{
	[TestClass]
	public class InterceptionTests
	{
		[TestMethod]
		public void QueryIsNotNull()
		{
			IQueryable<int> query = Enumerable.Range(1, 100).AsQueryable();
			IQueryable<int> interceptedQuery = query.Intercept(q => q.Execute());
			Assert.IsNotNull(interceptedQuery);
		}

		[TestMethod]
		public void QueryReturnsTheSameResult()
		{
			IQueryable<int> query = Enumerable.Range(1, 100).AsQueryable();
			IQueryable<int> interceptedQuery = query.Intercept(q => q.Execute());
			Assert.AreEqual(query.Sum(), interceptedQuery.Sum());
		}

		[TestMethod]
		public void InterceptMethodIsCalled()
		{
			Boolean isCalled = false;
			IQueryable<int> query = Enumerable.Range(1, 100).AsQueryable();
			IQueryable<int> interceptedQuery = query.Intercept(q =>
				{
					isCalled = true;
					return q.Execute();
				});

			interceptedQuery.ToList();
			Assert.IsTrue(isCalled);
		}

		[TestMethod]
		public void QueryResultCanBeReplaced()
		{
			IQueryable<int> query = Enumerable.Range(1, 100).AsQueryable();
			IQueryable<int> interceptedQuery = query.Intercept(q => { return 5; });
			Assert.AreEqual(interceptedQuery.First(), 5);
		}

		[TestMethod]
		public void ProviderCreateQueryIsSameAsTypedCreateQuery()
		{
			IQueryable<int> query = Enumerable.Range(1, 100).AsQueryable();
			IQueryable<int> interceptedQuery = query.Intercept(q => q.Execute());

			IQueryable query1 = interceptedQuery.Provider.CreateQuery(interceptedQuery.Expression);
			IQueryable<int> query2 = interceptedQuery.Provider.CreateQuery<Int32>(interceptedQuery.Expression);
			Assert.AreEqual(query1.Expression, query2.Expression);
		}
	}
}